package fina2.dcs.fi.validator;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.naming.InitialContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.context.ContextHelper;
import fina2.dcs.fis.BankLocal;

@Scope(ScopeType.SESSION)
@Name("fiAddBankValidator")
public class FiAddBankValidator implements Serializable{

	private Log log = Logging.getLog(getClass());

	private ResourceBundle bundle = null;
	private InitialContext ic = null;
	private BankLocal bl = null;

	public FiAddBankValidator() {
		try {
			UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();
			Locale l = root.getLocale();
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			bundle = ResourceBundle.getBundle("messages", l, cl);
			ic = ContextHelper.getInitialContext();
			bl = ContextHelper.injectBankLocal(ic);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public void validateCode(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		String val = value.toString().trim();
		if ((val.length() == 0) || (val.length() > 12)) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Illegal Code length");
			throw new ValidatorException(fm);
		} else if (bl.findByCode(val) != null) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Bank already exists");
			throw new ValidatorException(fm);
		}
	}

	public void validateName(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		String val = value.toString().trim();
		if ((val.length() == 0) || (val.length() > 255)) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Illegal length");
			throw new ValidatorException(fm);
		}
	}

}
